package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.config.properties.CmnyProperties;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.core.utils.MD5Util;
import com.csun.cmny.provider.model.domain.DmcCsunVersionFile;
import com.csun.cmny.provider.model.domain.DmcCsunVersionSet;
import com.csun.cmny.provider.model.dto.version.CheckFileVersionDto;
import com.csun.cmny.provider.model.dto.version.CsunVersionQueryDto;
import com.csun.cmny.provider.model.enums.device.DeviceFileUrlEnum;
import com.csun.cmny.provider.model.vo.csunversion.CsunVersionFileVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.DmcCsunVersionFileService;
import com.csun.cmny.provider.service.DmcCsunVersionSetService;
import com.csun.cmny.util.DateUtil;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2020-03-25 09:03
 * @Description: the class dmc csun version file controller
 */
@Slf4j
@RestController
@RequestMapping(value = "/csunVersion", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DmcCsunVersionFileController extends BaseController {

    @Resource
    private DmcCsunVersionFileService dmcCsunVersionFileService;
    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private DmcCsunVersionSetService dmcCsunVersionSetService;
    @Resource
    private CmnyProperties cmnyProperties;

    /**
     * 查看版本文件下载方式
     */
    @RequestMapping(value = "/queryFileUrlList", method = RequestMethod.POST)
    public Wrapper queryFileUrlList() {

        List<Map<String, String>> fileUrlList = DeviceFileUrlEnum.getMap2List();

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,
                cmnyMessageSource.getMessage("operation.success", null),
                fileUrlList);
    }

    /**
     * 查看版本列表
     *
     * @param csunVersionQueryDto
     *
     * @return
     */
    @RequestMapping(value = "/queryListWithPage", method = RequestMethod.POST)
    public Wrapper queryListWithPage(@RequestBody CsunVersionQueryDto csunVersionQueryDto) {

        List<CsunVersionFileVo> csunVersionFileVoList = dmcCsunVersionFileService.queryCsunVersionListWithPage(csunVersionQueryDto);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,
                cmnyMessageSource.getMessage("operation.success", null),
                new PageInfo<>(csunVersionFileVoList));
    }

    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.POST)
    public Wrapper deleteById(@PathVariable Long id) {

        // 判断是否在配置中
        DmcCsunVersionSet dmcCsunVersionSet = new DmcCsunVersionSet();
        dmcCsunVersionSet.setVersionId(id);
        int count = dmcCsunVersionSetService.selectCount(dmcCsunVersionSet);
        if (count > 0) { // 版本正在配置中
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("csun.version.file.setting", null));
        }

        DmcCsunVersionFile dmcCsunVersionFile = dmcCsunVersionFileService.selectByKey(id);

        Integer result = dmcCsunVersionFileService.deleteByKey(id);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        /**
         * @author  chisj
         * @date    2021-01-11
         * @desc    删除本地文件
         */
        if (dmcCsunVersionFile.getWay().equals(2)) {
            File file = new File(dmcCsunVersionFile.getPath());
            if (file.isFile() && file.exists()) {
                file.delete();
            }
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,
                cmnyMessageSource.getMessage("operation.success", null),
                result);
    }

    /**
     * 添加版本文件
     */
    @RequestMapping(consumes = "multipart/form-data", value = "/add", method = RequestMethod.POST)
    public Wrapper add(HttpServletRequest request) {

        Integer fileType = Integer.parseInt(request.getParameter("fileType"));
        if (PublicUtil.isEmpty(fileType)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("csun.version.file.type.null", null));
        }

        String fileVersion = request.getParameter("fileVersion");
        if (PublicUtil.isEmpty(fileVersion)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("csun.version.file.version.null", null));
        }

        String path = cmnyProperties.getCsun().getVersion().getFile().getPrefix();

        /**
         * @date    2020-04-28
         * @author  chisj
         * @desc    同一类型版本文件，版本编号不能重复
         */
        CheckFileVersionDto checkFileVersionDto = new CheckFileVersionDto();
        checkFileVersionDto.setFileType(fileType);
        checkFileVersionDto.setFileVersion(fileVersion);
        if (!dmcCsunVersionFileService.checkFileVersion(checkFileVersionDto)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("csun.version.file.version.conflict", null));
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> fileList = multipartRequest.getFiles("file");
        if (fileList.isEmpty()) {
//            return WrapMapper.error("文件不能为空");
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("csun.version.file.null", null));
        }

        byte[] buffer = null;
        String fileName = "";
        try {
            for (MultipartFile multipartFile : fileList) {
                fileName = multipartFile.getOriginalFilename();
                if (PublicUtil.isEmpty(fileName)) {
                    continue;
                }
                buffer = multipartFile.getBytes();

                /**
                 * @author  chisj
                 * @date    2021-01-11
                 * @desc    文件存储在本地
                 */
                path = path + DateUtil.nowDateStr() + "/" + fileName;
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
                multipartFile.transferTo(file);
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        DmcCsunVersionFile dmcCsunVersionFile = new DmcCsunVersionFile();
        dmcCsunVersionFile.setFileName(fileName);
        dmcCsunVersionFile.setFileType(fileType);
        dmcCsunVersionFile.setFileVersion(fileVersion);
//        dmcCsunVersionFile.setFileData(buffer);
        dmcCsunVersionFile.setLength(buffer.length);
        dmcCsunVersionFile.setMd5(MD5Util.getMD5String(buffer));
        dmcCsunVersionFile.setWay(2);
        dmcCsunVersionFile.setPath(path);
        //dmcCsunVersionFile.setBase64Md5(MD5Util.getMD5String(Base64.encodeBase64String(buffer)));

        dmcCsunVersionFileService.save(dmcCsunVersionFile);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null));
    }

    /**
     * 修改版本文件
     */
    @RequestMapping(consumes = "multipart/form-data", value = "/edit", method = RequestMethod.POST)
    public Wrapper edit(HttpServletRequest request) {

        String path = cmnyProperties.getCsun().getVersion().getFile().getPrefix();

        Long id = Long.parseLong(request.getParameter("id"));
        if (PublicUtil.isEmpty(id)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("csun.version.file.id.null", null));
        }

        // 根据id查询版本文件
        DmcCsunVersionFile dmcCsunVersionFile = dmcCsunVersionFileService.selectByKey(id);
        if (PublicUtil.isEmpty(id)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("csun.version.file.not.exist", null));
        }

        // 判断是否在配置中
        DmcCsunVersionSet dmcCsunVersionSet = new DmcCsunVersionSet();
        dmcCsunVersionSet.setVersionId(id);
        int count = dmcCsunVersionSetService.selectCount(dmcCsunVersionSet);
        if (count > 0) { // 版本正在配置中
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("csun.version.file.setting", null));
        }

        Integer fileType = Integer.parseInt(request.getParameter("fileType"));
        if (PublicUtil.isNotEmpty(fileType)) {
            dmcCsunVersionFile.setFileType(fileType);
        } else {
            fileType = dmcCsunVersionFile.getFileType();
        }

        String fileVersion = request.getParameter("fileVersion");
        if (PublicUtil.isNotEmpty(fileVersion)) {
            dmcCsunVersionFile.setFileVersion(fileVersion);
        } else {
            fileVersion = dmcCsunVersionFile.getFileVersion();
        }

        /**
         * @date    2020-04-28
         * @author  chisj
         * @desc    同一类型版本文件，版本编号不能重复
         */
        CheckFileVersionDto checkFileVersionDto = new CheckFileVersionDto();
        checkFileVersionDto.setId(id);
        checkFileVersionDto.setFileType(fileType);
        checkFileVersionDto.setFileVersion(fileVersion);
        if (!dmcCsunVersionFileService.checkFileVersion(checkFileVersionDto)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("csun.version.file.version.conflict", null));
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> fileList = multipartRequest.getFiles("file");
        String fileName = "";
        if (PublicUtil.isNotEmpty(fileList)) {
            byte[] buffer = null;
            try {
                for (MultipartFile multipartFile : fileList) {
                    fileName = multipartFile.getOriginalFilename();
                    if (PublicUtil.isEmpty(fileName)) {
                        continue;
                    }
                    buffer = multipartFile.getBytes();

                    /**
                     * @author  chisj
                     * @date    2021-01-11
                     * @desc    文件存储在本地
                     */

                    path = path + DateUtil.nowDateStr() + "/" + fileName;
                    File file = new File(path);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    file.createNewFile();
                    multipartFile.transferTo(file);
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            dmcCsunVersionFile.setFileName(fileName);
//            dmcCsunVersionFile.setFileData(buffer);
            dmcCsunVersionFile.setLength(buffer.length);
            dmcCsunVersionFile.setWay(2);
            dmcCsunVersionFile.setPath(path);
            dmcCsunVersionFile.setMd5(MD5Util.getMD5String(buffer));
        }

        //dmcCsunVersionFile.setBase64Md5(MD5Util.getMD5String(Base64.encodeBase64String(buffer)));

        dmcCsunVersionFileService.update(dmcCsunVersionFile);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null));
    }


    /**
     * 查询App版本
     *
     * @return the wrapper
     */
    @RequestMapping(value = "/queryAppVersion", method = RequestMethod.POST)
    public Wrapper queryAppVersion(@RequestBody CsunVersionQueryDto csunVersionQueryDto) {

        csunVersionQueryDto.setPageNum(1);
        csunVersionQueryDto.setPageSize(1);

        List<CsunVersionFileVo> csunVersionFileVoList = dmcCsunVersionFileService.queryCsunVersionListWithPage(csunVersionQueryDto);

        CsunVersionFileVo result = new CsunVersionFileVo();
        if (PublicUtil.isNotEmpty(csunVersionFileVoList)) {
            result = csunVersionFileVoList.get(0);
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,
                cmnyMessageSource.getMessage("operation.success", null),
                result);
    }
}
